package com.wxq.demo.config;

import com.wxq.demo.job.MySecondJob;
import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.SimpleTrigger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.*;

@Configuration
public class QuartzConfig {
    /**
     * JobDetail配置方式有两种，第一种方式通过MethodInvokingJobDetailFactoryBean进行配置
     * 只需要指定Job的实例名和调用的方法即可，这种方式无法在创建JobDetail时传递参数
     *
     * @return
     */
    @Bean
    MethodInvokingJobDetailFactoryBean jobDetailFactoryBean() {
        MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean();
        bean.setTargetBeanName("myFirstJob");
        bean.setTargetMethod("sayHello");
        return bean;
    }

    /**
     * 第二种方式是通过JobDetailFactoryBean进行配置，
     * 只需要指定JobClass即可，然后可以通过JobDataMap传递参数到Job中，Job中只需要提供属性名，
     * 并且提供一个相应的set方法即可接受参数
     *
     * @return
     */
    @Bean
    JobDetailFactoryBean factoryBean() {
        JobDetailFactoryBean bean = new JobDetailFactoryBean();
        bean.setJobClass(MySecondJob.class);
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("name", "wxq");
        bean.setJobDataMap(jobDataMap);
        bean.setDurability(true);
        return bean;
    }

    /**
     * Trigger配置常用的两种，第一种SimpleTriggerFactoryBean，
     *
     * @return
     */
    @Bean
    SimpleTriggerFactoryBean simpleTriggerFactoryBean() {
        SimpleTriggerFactoryBean bean = new SimpleTriggerFactoryBean();
        bean.setJobDetail(jobDetailFactoryBean().getObject());
        bean.setRepeatCount(3);//配置任务循环次数
        bean.setStartDelay(1000);//配置任务启动延迟时间
        bean.setRepeatInterval(2000);//配置任务的时间间隔
        return bean;
    }

    /**
     * CronTriggerFactoryBean方式是使用Cron表达式
     *
     * @return
     */
    @Bean
    CronTriggerFactoryBean cronTriggerFactoryBean() {
        CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
        bean.setJobDetail(factoryBean().getObject());
        bean.setCronExpression("* * * * * ?");
        return bean;
    }

    /**
     * 最后通过SchedulerFactoryBean配置Trigger就可以实现定时任务配置
     *
     * @return
     */
    @Bean
    SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        SimpleTrigger simpleTrigger = simpleTriggerFactoryBean().getObject();
        CronTrigger cronTrigger = cronTriggerFactoryBean().getObject();
        bean.setTriggers(simpleTrigger, cronTrigger);
        return bean;
    }
}
